package cn.org.mrliu.ssm.common.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

/**
 * 设置是否允许Ajax跨域请求,默认为false,如果需要,设置init参数的isAccess为true
 * @author MrLiu
 *
 */
public class AjaxAccessControlFilter implements Filter{
	private boolean isAccess = false;
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		if (isAccess) {
			//httpResponse.addHeader("Access-Control-Allow-Origin","*");
			httpResponse.setHeader("Access-Control-Allow-Origin","*");
		}
		filterChain.doFilter(request, httpResponse);
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		String isAccessString = filterConfig.getInitParameter("isAccess");
		if ("true".equals(isAccessString)) {
			isAccess = true;
			System.out.println("------------------------------------ 允许Ajax跨域请求,请检查是否是开发模式,否则,应该关闭 ------------------------------------");
		}else{
			isAccess = false;
			System.out.println("----------- 不允许Ajax跨域请求,如果是开发模式,需要跨域请求,请设置AjaxAccessControlFilter的init参数isAccess为true---------------");
		}
	}

}
